package com.taotao.wechat.game;

import com.rop.client.CompositeResponse;
import com.taotao.admin.MyRopClient;
import com.taotao.rop.database.domain.PlayGame;
import com.taotao.rop.database.domain.PlayGameRanking;
import com.taotao.rop.response.BaseResponse;
import com.taotao.rop.util.DateTimeUtil;
import com.taotao.wechat.message.resp.Article;
import com.taotao.wechat.message.resp.BaseMessage;
import com.taotao.wechat.message.resp.NewsMessage;
import com.taotao.wechat.message.resp.TextMessage;
import com.taotao.wechat.util.MessageUtil;
import com.taotao.wechat.util.ValidateUtil;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 单日争霸赛
 * 翻牌游戏一：2015年2月4日-3月22日
 * 规则：
 * 输入【找4G】关键词，再根据系统提示输入【内蒙古移动手机号码】，点击进入游戏页面就可参与活动；
 * 活动采用单日排名获奖制（如游戏分数相同，将按照活动时间顺序进行排名）；
 * 每日参与游戏次数仅限一次（如下载【手机营业厅】客户端获取【次数代码】后，每日参与次数可增加一次）；
 * 用户游戏分数排名以每日最高一次分数进行记录，游戏起始时间为60秒；
 * 注意：每位内蒙古移动用户只可获得其中一日排名奖项，获得后将不能再参与活动
 */
public class FindWordGame2 extends Game {
    public static final boolean IS_ENABLE = true;
    private static final String game_url_format = "/game/findWord2/index.html?appId=%s&openId=%s&tel=%s";
    public static final String MSG_TEL_IS_RANKING = "此手机号已经中奖";
    public static final String MSG_TEL_IS_USED = "此手机号码已经被使用";
    public static final String MSG_TEL_IS_USED_NO_MEMBER = "此手机号码已经被使用，请领取升级码继续参与";

    public FindWordGame2(){}

    public FindWordGame2(BaseMessage baseMessage, String content, String appKey) {
        super(baseMessage, content, appKey);
    }


    protected String inputGameName2() {
        if (!content.equalsIgnoreCase(getName())) {
            return "";
        }
        //插入playgame表，准备开始游戏
        PlayGame playGame = new PlayGame();
        playGame.setAppId(appKey);
        playGame.setOpenId(baseMessage.getToUserName());
        playGame.setGameName(getNickName());
        MyRopClient.getRopClient("").buildClientRequest()
                .post(playGame, BaseResponse.class, "playGame.insert", "1.0");

        TextMessage textMessage = new TextMessage(baseMessage);
        textMessage.setContent("请输入内蒙移动手机号码查询【找4G】游戏成绩");
        return MessageUtil.textMessageToXml(textMessage);
    }

    protected String inputTelephone2() {
        //判断属于哪款游戏
        String currentGameName = getLatestInputGameName(baseMessage.getToUserName(), appKey);
        if (StringUtils.isBlank(currentGameName) || !currentGameName.equalsIgnoreCase(getNickName())) {
            return "";
        }

        TextMessage textMessage = new TextMessage(baseMessage);
        //判断是否是内蒙移动手机号
        int telType = ValidateUtil.isYiDong(content);
        if (telType != 0) {
            if (telType == -1) {
                textMessage.setContent(getMsgTelNotKnow());
            } else if (telType == 1) {
                textMessage.setContent(getMsgTelNotNeiMengCMCC());
            } else if (telType == -2) {
                return "";
            } else if (telType == -3) {
                textMessage.setContent(msgTelException);
            }
            return MessageUtil.textMessageToXml(textMessage);
        }

        //判断今天是否输入过游戏名字
        if (!hasInputGameNameToday(baseMessage.getToUserName(), appKey)) {
            textMessage.setContent(getMsgTelWithoutGameName());
        } else {
            //判断手机号是否中奖
            String result = telJoinCountToday(content, baseMessage.getToUserName(), appKey);
            if (StringUtils.isNotBlank(result) && result.contains(MSG_TEL_IS_RANKING)) {
                textMessage.setContent(result);
            } else {
                textMessage.setContent("很遗憾，在找4G活动中您未中奖，感谢您的支持。");
            }
        }
        return MessageUtil.textMessageToXml(textMessage);
    }

    public String queryPrize() {
        if (StringUtils.isBlank(getAppIds()) || getAppIds().contains(appKey)) {
            String result = inputGameName2();
            if (StringUtils.isNotBlank(result)) {
                return result;
            }

            result = inputTelephone2();
            if (StringUtils.isNotBlank(result)) {
                return result;
            }

        }
        return "";
    }



    @Override
    public String getAppIds() {
        return "";
    }

    @Override
    public String getMemberCode() {
        return "4GPNGCJ";
    }

    @Override
    public Integer getMemberStatus() {
        return 2;
    }

    @Override
    public String getName() {
        return "找4G";
    }

    @Override
    public String getNickName() {
        return "findWord2";
    }

    @Override
    public String getStartDate() {
        return "2015-02-04";
    }

    @Override
    public String getEndDate() {
        return "2015-03-23";
    }

    @Override
    public String getMsgUpgradeMemberSuccess() {
        return "恭喜您成功将游戏次数升级为2次，祝您拿到好排名";
    }

    @Override
    public String getMsgUpgradeMemberFailure() {
        return "很遗憾，升级失败，请核对【次数代码】";
    }

    @Override
    public String getMsgGameNotStart() {
        return "亲您也太心急了，我们的【找4G】游戏还没有开始呢！";
    }

    @Override
    public String getMsgGameIsEnd() {
        return "【找4G】活动已经结束。";
    }

    @Override
    public String getMsgAfterGameName() {
        return "请输入内蒙移动手机号码参与【找4G】游戏";
    }

    @Override
    public String getMsgTelWithoutGameName() {
        return "请先输入【找4G】关键词或点击【我要精彩】按键";
    }

    @Override
    public String wechatJoinCountToday(String openId, String appKey) {
        //已经中奖的微信号不允许再次参加活动
        PlayGameRanking wechatCondition = new PlayGameRanking();
        wechatCondition.setAppId(appKey);
        wechatCondition.setOpenId(openId);
        wechatCondition.setGameName(getNickName());
        CompositeResponse<BaseResponse> rankResponse = MyRopClient.getRopClient("").buildClientRequest()
                .post(wechatCondition, BaseResponse.class, "playGameRanking.list", "1.0");
        if (rankResponse.isSuccessful()) {
            BaseResponse baseResponse = rankResponse.getSuccessResponse();
            if (baseResponse.getSuccess()) {
                List<LinkedHashMap<String, Object>> respData = (List<LinkedHashMap<String, Object>>) baseResponse.getData();
                if (respData != null && respData.size() > 0) {
                    //已经中奖
                    for (LinkedHashMap<String, Object> map : respData) {
                        if (map.get("finishTime") != null && StringUtils.isNotBlank(map.get("finishTime").toString())
                                || map.get("prize") != null && StringUtils.isNotBlank(map.get("prize").toString())
                                || map.get("result") != null && StringUtils.isNotBlank(map.get("result").toString())) {
                            String prize = map.get("prize").toString();
                            String result = map.get("result").toString();
                            String finishTime = DateTimeUtil.parseDate(Long.parseLong(map.get("finishTime").toString()));
                            String tel = map.get("tel").toString();

                            return "您的手机号码" + tel + "，在" + finishTime + "找到" + result + "个4G，获得" + prize + "元话费，谢谢参与~";
                        }
                    }
                }
            }
        }

        PlayGame condition = new PlayGame();
        condition.setAppId(appKey);
        condition.setOpenId(openId);
        condition.setGameName(getNickName());

        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient("").buildClientRequest()
                .post(condition, BaseResponse.class, "playGame.getJoinCountToday", "1.0");
        if (response.isSuccessful()) {
            BaseResponse baseResponse = response.getSuccessResponse();
            if (baseResponse.getSuccess()) {
                int count = (Integer) baseResponse.getData();
                if (isMember(openId, appKey, getMemberStatus())) {
                    if (count >= 2) {
                        return "您今天的次数已经用完";
                    } else if (count == 1){
                        return isMemberTimes;
                    } else {
                        return "";
                    }
                } else {
                    if (count >= 1) {
                        return "领取升级码，可获得一个额外次数";
                    } else {
                        return "";
                    }
                }
            }
        }
        return "系统繁忙，请您稍后再试";
    }

    @Override
    public String telJoinCountToday(String tel, String openId, String appKey) {
        //已经中奖的手机号不允许再次参加活动
        PlayGameRanking telCondition = new PlayGameRanking();
        telCondition.setTel(tel);
        telCondition.setGameName(getNickName());
        CompositeResponse<BaseResponse> rankResponse = MyRopClient.getRopClient("").buildClientRequest()
                .post(telCondition, BaseResponse.class, "playGameRanking.list", "1.0");
        if (rankResponse.isSuccessful()) {
            BaseResponse baseResponse = rankResponse.getSuccessResponse();
            if (baseResponse.getSuccess()) {
                List<LinkedHashMap<String, Object>> respData = (List<LinkedHashMap<String, Object>>) baseResponse.getData();
                if (respData != null && respData.size() > 0) {
                    //已经中奖
                    for (LinkedHashMap<String, Object> map : respData) {
                        if (map.get("finishTime") != null && StringUtils.isNotBlank(map.get("finishTime").toString())
                                || map.get("prize") != null && StringUtils.isNotBlank(map.get("prize").toString())
                                || map.get("result") != null && StringUtils.isNotBlank(map.get("result").toString())) {
                            String prize = map.get("prize").toString();
                            String result = map.get("result").toString();
                            String finishTime = DateTimeUtil.parseDate(Long.parseLong(map.get("finishTime").toString()));

                            return MSG_TEL_IS_RANKING + "，在" + finishTime + "找到" + result + "个4G，获得" + prize + "元话费，谢谢参与~";
                        }
                    }
                }
            }
        }

        PlayGame condition = new PlayGame();
//        condition.setAppId(appKey);
//        condition.setOpenId(openId);
        condition.setTel(tel);
        condition.setGameName(getNickName());

        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient("").buildClientRequest()
                .post(condition, BaseResponse.class, "playGame.getTelJoinCountToday", "1.0");
        if (response.isSuccessful()) {
            BaseResponse baseResponse = response.getSuccessResponse();
            if (baseResponse.getSuccess()) {
                int count = (Integer) baseResponse.getData();
                if (isMember(openId, appKey, getMemberStatus())) {
                    if (count >= 2) {
                        return MSG_TEL_IS_USED;
                    } else {
                        return "";
                    }
                } else {
                    if (count >= 1) {
                        return MSG_TEL_IS_USED_NO_MEMBER;
                    } else {
                        return "";
                    }
                }
            }
        }
        return "系统繁忙，请您稍后再试";
    }

    @Override
    protected String gameUrl() {
        String url = MyRopClient.BASE_URL + String.format(game_url_format, appKey, baseMessage.getToUserName(), content);
        NewsMessage newsMessage = new NewsMessage(baseMessage);
        newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
        newsMessage.setArticleCount(1);
        Article article = new Article();
        article.setDescription("高手过招的时刻到了！2月4日-3月22日，凡通过“内蒙古移动营业厅”或各盟市分公司公众号参与“找4G赢话费”活动，每天排名前一百的用户都可获得相应的话费奖励，最高200元哦！");
        article.setPicUrl(MyRopClient.BASE_URL + "/game/findWord2/img/zt.jpg");
        article.setTitle("“找4G”单日争霸赛开始啦！！");
        article.setUrl(url);
        List<Article> articles = new ArrayList<Article>();
        articles.add(article);
        newsMessage.setArticles(articles);
        return MessageUtil.newsMessageToXml(newsMessage);
    }
}
